﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Message
{
    /// <summary>CCPSIP_062：取得歷史訊息</summary>

    public class load_history_msg : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數，驗證身分
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string ChatID = req.Form["ChatID"];         //聊天ID(對方帳號或ClientGID)
                Int64 Pid = 0;
                if (String.IsNullOrEmpty(Convert.ToString(req.Form["Pid"])))
                    Pid = Int32.MaxValue;   //2147483647
                else
                    Pid = Convert.ToInt64(req.Form["Pid"]);   //從pid這則訊息開始往前算

                int MessageCount = Convert.ToInt32(req.Form["MessageCount"]);    //取得歷史訊息的筆數

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置


                //【02】取得歷史訊息
                Dictionary<string, object> resultDict = null;
                if (SipKit.isGroupID(ChatID))
                    resultDict = OracleKitMsg.GetHistoryGroupMsgs(userInfo, ChatID, Pid, MessageCount);
                else
                    resultDict = OracleKitMsg.GetHistoryOneOneMsgs(userInfo, ChatID, Pid, MessageCount);


                //【99】回傳結果
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(resultDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}